<template>
  <div
    v-if="modelValue"
    class="m-4 mx-auto w-full max-w-[80%] rounded-lg p-4 shadow"
    :class="theme"
    role="alert"
  >
    <div class="mb-4 flex items-center justify-between">
      <span class="text-base font-semibold uppercase">{{ title }}</span>
      <ZButton class="btn-circle btn-xs" @click="close()">
        <template #icon>
          <span class="icon-[uil--multiply]"></span>
        </template>
      </ZButton>
    </div>
    <div class="flex items-center">
      <slot>
        <div class="text-sm font-normal">
          {{ message }}
        </div>
      </slot>
    </div>
  </div>
</template>
<script setup lang="ts">
import { NoticeType } from "./types";
import { isNumber } from "./utils";

interface Props {
  modelValue?: boolean;
  type?: NoticeType;
  title: string;
  message?: string;
  duration?: number;
  name?: string;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: true,
  type: "default",
});
const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  close: [name: string | undefined];
}>();

const themes = {
  default: ["bg-base-200", "text-base-content"],
  info: ["bg-info", "text-white"],
  success: ["bg-success", "text-white"],
  warning: ["bg-warning", "text-white"],
  error: ["bg-error", "text-white"],
};

const theme = computed(() => {
  return themes[props.type];
});

const close = () => {
  if (!props.modelValue) return;
  // 更新 modelValue
  emit("update:modelValue", false);
  emit("close", props.name);
};

// 自动关闭
watch(
  () => props.modelValue,
  (val) => {
    if (val && isNumber(props.duration)) setTimeout(close, props.duration);
  },
  { immediate: true },
);
</script>
